package com.mathlearning.auth.service;

import com.mathlearning.auth.dto.learning.*;
import com.mathlearning.auth.entity.*;
import com.mathlearning.auth.repository.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserLearningService {

    @Autowired
    private UserSubmissionRepository userSubmissionRepository;

    @Autowired
    private DiscussionRepository discussionRepository;

    @Autowired
    private DiscussionTagRepository discussionTagRepository;

    @Autowired
    private ProblemRepository problemRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取学习统计数据
     */
    public LearningStatsResponse getLearningStats(Long userId) {
        // 查询答题记录统计
        Long totalProblems = userSubmissionRepository.countByUserId(userId);
        Long correctProblems = userSubmissionRepository.countCorrectByUserId(userId);
        Long wrongProblems = totalProblems - correctProblems;
        
        // 计算正确率
        Integer accuracy = totalProblems > 0 ? 
            (int) (correctProblems * 100 / totalProblems) : 0;
        
        // 查询连续学习天数和总学习时长
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        Integer continuousDays = user.getContinuousLearningDays();
        Integer totalStudyMinutes = user.getTotalStudyMinutes() != null ? user.getTotalStudyMinutes() : 0;
        
        // 查询本周答题数（从本周一到今天）
        LocalDate today = LocalDate.now();
        LocalDate mondayOfWeek = today.with(java.time.temporal.TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
        java.time.LocalDateTime weekStart = mondayOfWeek.atStartOfDay();
        java.time.LocalDateTime weekEnd = today.atTime(23, 59, 59);
        
        Long weekProblemsCount = userSubmissionRepository.countDistinctProblemsByDateRange(userId, weekStart, weekEnd);
        Integer weekProblems = weekProblemsCount != null ? weekProblemsCount.intValue() : 0;
        
        return LearningStatsResponse.builder()
            .totalProblems(totalProblems.intValue())
            .correctProblems(correctProblems.intValue())
            .wrongProblems(wrongProblems.intValue())
            .accuracy(accuracy)
            .continuousDays(continuousDays)
            .weekProblems(weekProblems)
            .totalStudyMinutes(totalStudyMinutes)
            .build();
    }

    /**
     * 获取学习记录列表
     */
    public Map<String, Object> getMyLearning(Long userId) {
        // 查询用户所有答题记录
        List<UserSubmission> submissions = userSubmissionRepository
            .findAllByUserIdOrderBySubmitTimeDesc(userId);
        
        // 组装数据
        List<LearningRecordResponse> list = submissions.stream()
            .map(submission -> {
                Problem problem = problemRepository.findById(submission.getProblemId())
                    .orElse(null);
                
                if (problem == null) {
                    return null;
                }
                
                return LearningRecordResponse.builder()
                    .id(submission.getId())
                    .problemId(submission.getProblemId())
                    .title(problem.getTitle())
                    .difficulty(problem.getDifficulty())
                    .isCorrect("accepted".equals(submission.getStatus()))
                    .score(submission.getScore())
                    .submitTime(submission.getSubmitTime())
                    .answer(submission.getAnswer())
                    .build();
            })
            .filter(record -> record != null)
            .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        return result;
    }

    /**
     * 获取帖子统计数据
     */
    public PostsStatsResponse getPostsStats(Long userId) {
        Long totalPosts = discussionRepository.countByAuthorId(userId);
        Long totalViews = discussionRepository.sumViewsByAuthorId(userId);
        Long totalLikes = discussionRepository.sumLikesByAuthorId(userId);
        Long totalComments = discussionRepository.sumCommentsByAuthorId(userId);
        
        return PostsStatsResponse.builder()
            .totalPosts(totalPosts != null ? totalPosts.intValue() : 0)
            .totalViews(totalViews != null ? totalViews.intValue() : 0)
            .totalLikes(totalLikes != null ? totalLikes.intValue() : 0)
            .totalComments(totalComments != null ? totalComments.intValue() : 0)
            .build();
    }

    /**
     * 获取我的帖子列表
     */
    public Map<String, Object> getMyPosts(Long userId) {
        // 查询用户所有帖子
        List<Discussion> discussions = discussionRepository
            .findAllByAuthorIdOrderByCreatedAtDesc(userId);
        
        // 组装数据
        List<MyPostResponse> list = discussions.stream()
            .map(discussion -> {
                // 获取标签
                List<String> tags = discussionTagRepository
                    .findByDiscussionId(discussion.getId())
                    .stream()
                    .map(DiscussionTag::getTagName)
                    .collect(Collectors.toList());
                
                // 截取内容（前200字）
                String content = discussion.getContent();
                if (content != null && content.length() > 200) {
                    content = content.substring(0, 200) + "...";
                }
                
                return MyPostResponse.builder()
                    .id(discussion.getId())
                    .title(discussion.getTitle())
                    .content(content)
                    .tags(tags)
                    .views(discussion.getViews())
                    .likes(discussion.getLikes())
                    .comments(discussion.getComments())
                    .createTime(discussion.getCreatedAt())
                    .build();
            })
            .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        return result;
    }

    /**
     * 获取用户在指定年月的学习记录日期
     */
    public LearningDatesResponse getLearningRecordDates(Long userId, Integer year, Integer month) {
        // 如果年月为空，使用当前年月
        LocalDate now = LocalDate.now();
        if (year == null) {
            year = now.getYear();
        }
        if (month == null) {
            month = now.getMonthValue();
        }
        
        // 查询数据库获取学习记录日期
        List<java.sql.Date> learningDates = userSubmissionRepository
            .findLearningDatesByUserIdAndYearMonth(userId, year, month);
        
        // 格式化为 YYYY-MM-DD 字符串
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        List<String> dateStrings = learningDates.stream()
            .map(sqlDate -> sqlDate.toLocalDate().format(formatter))
            .collect(Collectors.toList());
        
        return LearningDatesResponse.builder()
            .year(year)
            .month(month)
            .dates(dateStrings)
            .totalDays(dateStrings.size())
            .build();
    }
}



